package com.showcai.service.impl;

import com.showcai.log.LogFactory;
import com.showcai.myRunTime.MyRunTimeExcption;
import com.showcai.redis.RedisCache;
import com.showcai.result.ReturnCode;
import com.showcai.service.TokenService;
import com.showcai.util.GenerateID;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Created by Baggio on 2018-2-5.
 */
@Service
public class TokenServiceImpl implements TokenService {

    protected Logger logger = LogFactory.getLogger(getClass());
    @Autowired
    RedisCache redisCache;

    @Override
    public String createToken() throws MyRunTimeExcption {
        String token = null;
        try {
            logger.info("token正在随机生成————————");
            token = GenerateID.getRandomNum(10, GenerateID.IS_NOT_ONLY_NUMBER);
            String value = (String) redisCache.put(token, token, 120);
            logger.info("存入的值为————————————————"+value);
            logger.info("token已经生成完毕————————"+token);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyRunTimeExcption(ReturnCode.TOKEN_IS_CREATE_FAIL.getCode(),ReturnCode.TOKEN_IS_CREATE_FAIL.getMsg());
        }
        return token;
    }

    @Override
    public Boolean verifyToken(String token) throws MyRunTimeExcption {


        if (StringUtils.isBlank(token)) {
            logger.info("token is not 存在");
            throw new MyRunTimeExcption(ReturnCode.TOKEN_IS_INEXISTENCE);
        }

        try {
            String sysToken = (String) redisCache.get("token");
            if (StringUtils.isNotBlank(sysToken)) {
                logger.info("token is not 有效");
                throw new MyRunTimeExcption(ReturnCode.TOKEN_IS_INVALID);

            }
            redisCache.put(token, token, 30);
        } catch (Exception e) {
            e.printStackTrace();
            throw new MyRunTimeExcption(ReturnCode.TOKEN_IS_INVALID);
        }

        return true;
    }
}
